package org.bright.controller;

import org.bright.entity.Employee;
import org.bright.entity.R;
import org.bright.enums.HttpEnum;
import org.bright.service.EmployeeService;
import org.bright.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;

@RestController
@RequestMapping("/employee")
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/insertEmp")
    public R insertEmp(@Valid Employee employee, @RequestParam("empImagePath") MultipartFile empImagePath, HttpServletRequest request) {
        String imgPath;
        try {
            if (empImagePath != null && !empImagePath.isEmpty()) {
                imgPath = FileUtil.upload(request, empImagePath);
                if (imgPath != null) {
                    // 将上传图片的地址封装到实体类
                    employee.setImagePath(imgPath);
                    System.out.println("-----------------图片上传成功！");
                } else {
                    System.out.println("-----------------图片上传失败！");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("----------------图片上传失败！");
        }

        int count = employeeService.insertInto(employee);

        return count > 0 ? R.success("用户新增成功") : R.fail(HttpEnum.ERROR.getCode(), "用户新增失败");
    }

    @GetMapping("getList")
    public R getList(@RequestParam("pageNum") Integer pageNum){
        return R.success(employeeService.getPage(pageNum));
    }
}